package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"pets/cache"
	"pets/models"
	"pets/pkg"
	"time"
)

type UserController struct {
	beego.Controller
}
type Res struct {
	Code     int         `json:"code"`
	Data     interface{} `json:"data"`
	Database string      `json:"database"`
}

func (c *UserController) Login() {
	username := c.GetString("username")
	Password := c.GetString("password")
	var user models.User
	key := "pwd_error" + username
	count, _ := cache.Rdb.Get(cache.Ctx, key).Int()
	if count >= 3 {
		c.Data["json"] = Res{
			Code:     500,
			Data:     nil,
			Database: "密码错误三次,封禁两小时",
		}
		c.ServeJSON()
		return
	}
	models.DB.Debug().Where("username=?", username).Find(&user)
	if username == "" || Password == "" {
		c.Data["json"] = Res{
			Code:     500,
			Data:     nil,
			Database: "参数不能为空",
		}
		c.ServeJSON()
		return
	}
	if user.ID == 0 {
		c.Data["json"] = Res{
			Code:     500,
			Data:     nil,
			Database: "该用户不存在",
		}
		c.ServeJSON()
		return
	}
	if user.Password != pkg.MD5(Password) {
		cache.Rdb.Incr(cache.Ctx, key)
		if count == 2 {
			cache.Rdb.Expire(cache.Ctx, key, time.Hour*2)
		}
		c.Data["json"] = Res{
			Code:     500,
			Data:     nil,
			Database: "密码错误",
		}
		c.ServeJSON()
		return
	}
	models.DB.Debug().Find(&user)
	c.Data["json"] = Res{
		Code:     200,
		Data:     nil,
		Database: "登陆成功",
	}
	c.ServeJSON()
	return
}
func (c *UserController) List() {
	var user []models.PetData
	models.DB.Debug().Model(&models.PetTypes{}).
		Select("pet_types*, pet_types.name,pet_types.types").
		Joins("join users on pet_types.userid = users.id").
		Scan(&user)
	c.Data["json"] = Res{
		Code:     200,
		Data:     user,
		Database: "查询成功",
	}
	c.ServeJSON()
	return
}
